<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>

        <el-card>
            <el-row>
                <el-col>
                    <el-button type="primary" @click="addrole">添加角色</el-button>
                </el-col>
            </el-row>
            <el-table :data="roleslist" border stripe>
                <el-table-column type="expand">
                <template slot-scope="scope">
                    <el-row :class="['bdbottom',index==0?'bdtop':'' ,'vcenter']" v-for="(item1,index) in scope.row.children " :key="item1.id">
                        <el-col :span="5">
                            <el-tag  closable @close="removerolebyid(scope.row,item1.id)">{{item1.authName}}</el-tag>
                            <i class="el-icon-caret-right"></i>
                        </el-col>
                        <el-col :span="19">
                            <el-row :class="[index==0?'':'bdtop','vcenter']" v-for="(item2,index) in item1.children" :key="item2.id">
                                <el-col :span="6">
                                    <el-tag type="success" closable 
                                    @close="removerolebyid(scope.row,item2.id)">{{item2.authName}}</el-tag>
                                    <i class="el-icon-caret-right"></i>
                                </el-col>
                                <el-col :span="18">
                                    <el-tag type="warning" v-for="item3 in item2.children"  closable :key="item3.id"
                                    @close="removerolebyid(scope.row,item3.id)">{{item3.authName}}</el-tag>
                                </el-col>
                            </el-row>
                        </el-col>
                    </el-row> 
                    </template>
                </el-table-column>
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column prop="roleName" label="角色名称"></el-table-column>
                <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
                <el-table-column  label="操作">
                    <template slot-scope="scope">
                        <el-button size="mini" type="primary" icon="el-icon-edit" @click="roleedit(scope.row.id)">编辑</el-button>
                        <el-button size="mini" type="danger" icon="el-icon-delete" @click="roledelete(scope.row.id)">删除</el-button>
                        <el-button size="mini" type="warning" icon="el-icon-setting" @click="showsetrightdialog(scope.row)">分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!---分页还可以继续写--->
        <el-pagination
            background
            layout="prev, pager, next"
            :total="4">
        </el-pagination>
        <el-dialog title="添加角色" :visible.sync="roledialogFormVisible">
                <el-form :model="rolefrom" :rules="rolerules" ref="roleruleForm">
                    <el-form-item label="角色名称" prop="roleName" >
                        <el-input v-model="rolefrom.roleName" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述" prop="roleDesc">
                        <el-input v-model="rolefrom.roleDesc" autocomplete="off"></el-input>
                    </el-form-item>       
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button type='danger'  @click="roledialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addrloesure">确 定</el-button>
                </div>
      </el-dialog> 
      <el-dialog title="修改角色" :visible.sync="editroledialogFormVisible">
                <el-form :model="editrolefrom" :rules="rolerules" ref="editroleruleForm">
                    <el-form-item label="角色名称" prop="roleName" >
                        <el-input v-model="editrolefrom.roleName" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述" prop="roleDesc">
                        <el-input v-model="editrolefrom.roleDesc" autocomplete="off"></el-input>
                    </el-form-item>       
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button type='danger'  @click="editroledialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="editrolesure">确 定</el-button>
                </div>
      </el-dialog> 
      <el-dialog
        title="分配权限"
        :visible.sync="setrightsdialogVisible"
        width="50%"
        @close="setrightclosed">
        <el-tree show-checkbox node-key="id" default-expand-all :default-checked-keys="defkes" :data="rightaddlist" 
        ref="treeref" :props="treeProps" ></el-tree>
        <span slot="footer" class="dialog-footer">
            <el-button @click="setrightsdialogVisible = false">取 消</el-button>
            <el-button type="primary"  @click="allotrights">确 定</el-button>
        </span>
    </el-dialog>        
    </div>
</template>

<script>
export default {
    data() {
        return {
            roleslist:[],
            roledialogFormVisible:false,
            editroledialogFormVisible:false,
            setrightsdialogVisible:false,
            roleId:'',
            rolefrom:{
                roleName:'',
                roleDesc:''
            },
            rightaddlist:[],
            editrolefrom:{},
            rolerules:{
                roleName:[ { required: true, message: '请输入角色名', trigger: 'blur' },
                { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }],
                roleDesc:[ { required: true, message: '请输入角色描述', trigger: 'blur' },
                { min: 5, max: 10, message: '长度在 5 到 10 个字符', trigger: 'blur' }]
            },
            treeProps:{
                label:'authName',
                children:'children'
            },
            defkes:[]
        }
    },
    created(){
        this.getroleslist()
    },
    methods:{
       async getroleslist(){
         const {data:res} = await this.$http.get('roles')
         if(res.meta.status!==200) return this.$message.error("请求数据失败")
         this.roleslist = res.data
        
        },
        addrole(){
            this.roledialogFormVisible = true
        },
        async addrloesure(){
            this.roledialogFormVisible = false
            const {data:res} = await this.$http.post('roles',this.rolefrom)
            
            if(res.meta.status!=201) return this.$message.error("创建角色失败")
            this.$message.success("创建角色成功")
            this.getroleslist()   
        },
        async roleedit(id){
            this.editroledialogFormVisible=true
            const {data:res} = await this.$http.get('roles/'+id)
            this.editrolefrom = res.data 
        },
        editrolesure(){
            this.$refs.editroleruleForm.validate(async vaild=>{
                if(!vaild) return this.$message.error("请按要求提交信息") 
                const {data:res} =await this.$http.put('roles/'+this.editrolefrom.roleId,this.editrolefrom)
                if(res.meta.status!=200) return this.$message.error("修改角色失败")
                this.editroledialogFormVisible = false
                this.getroleslist()
                this.$message.success("修改用户角色成功")
                
            })
        },
        async roledelete(id){
        const res = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
        }).catch(err=>{
            return err
        })
         if(res!='confirm') {
            return this.$message.info("已取消当前删除操作")
        }
        const {data:ruesult} = await this.$http.delete("roles/"+id)
        if(ruesult.meta.status!=200) return this.$message.error("删除用户失败")
        this.$message.success("成功删除当前用户")
        this.getroleslist()
        },

       async removerolebyid(role,rightid){
        const res = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
        }).catch(err=>err)
        if(res!='confirm'){
            return this.$message.info("取消了删除")
        }
        const {data:rest} = await this.$http.delete(`roles/${role.id}/rights/${rightid}`)
        if(rest.meta.status!=200) return this.$message.error("删除权限失败")
        this.$message.success("删除权限成功")
        role.children = rest.data
        },
        async showsetrightdialog(role){
        this.roleId = role.id
        const {data:res}  =await this.$http.get('rights/tree')
        if(res.meta.status!=200) return this.$message.error("获取权限信息失败")
        this.rightaddlist = res.data
        //递归获取3级节点的id
        this.getrefkeys(role,this.defkes)
        this.setrightsdialogVisible=true
        },
        getrefkeys(node,arr){
            if(!node.children){
                return arr.push(node.id)
            }           
            node.children.forEach(item => {
                this.getrefkeys(item,arr)
            });
        },
        setrightclosed(){
            this.defkes=[]
        },
       async allotrights(){
            const keys = [
            ...this.$refs.treeref.getCheckedKeys(),...this.$refs.treeref.getHalfCheckedKeys()
            ]
            const idstr = keys.join(',')
            const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{
             rids:idstr
            })
            if(res.meta.status!=200) return this.$message.error("更新权限失败")
            this.$message.success("更新权限成功")
            this.getroleslist()
            this.setrightsdialogVisible = false
        }
        
    }
}
</script>

<style scoped>
.el-tag{
    margin: 7px;
}
.bdtop{
    border-top: 1px solid #eee;
}
.bdbottom{
    border-bottom: 1px solid #eee;
}
.vcenter{
    display: flex;
    align-items: center;
}
</style>